<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.partner_view" @click="rowView(row)">详 情</el-button>
        <el-button type="text" icon="el-icon-edit" size="small" v-if="permission.partner_edit" @click.stop="handleEdit(row)">编 辑 </el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.partner_delete" @click="rowDel(row)">删 除 </el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.partner_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.partner_delete" @click="handleDelete(row)">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="locations">
        <el-tag v-for="(item, index) in row.locations" :key="index">{{ item.name }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog v-dragDirectives :title="title" append-to-body :visible.sync="addDialog" @close="closeDialog">
      <avue-form v-if="addDialog" ref="addProperties" v-model="properties" :option="propertiesOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="addDialog = false">取 消</el-button>
        <el-button
          v-if="title != '详情'"
          type="primary"
          size="small"
          :icon="title == '新增' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'"
          @click="submit"
          v-preventReClick
          >{{ title == '新增' ? '保 存' : '修 改' }}</el-button
        >
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getPartnerScmDefault, checkScmTenant } from '@/api/admin/partner';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'AdminPartner',
  components: {
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ADMIN_PARTNER',
      tableOption: {},
      form: {},
      query: {},
      addDialog: false,
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 410px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        // searchMenuPosition: 'right',
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        searchLabelWidth: 90,
        column: [
          {
            label: '供应商编码',
            prop: 'code',
            search: true,
            searchSpan: 6,
            rules: [
              {
                required: true,
                message: '请输入供应商编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商名称',
            prop: 'name',
            searchSpan: 6,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入供应商名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商缩写',
            prop: 'abbreviation',
            search: true,
            searchSpan: 6,
            rules: [
              {
                required: true,
                message: '请输入供应商缩写',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '部门/职位',
            prop: 'position'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '供应商地址',
            prop: 'address'
          },
          {
            label: 'SCM启用',
            prop: 'openScm',
            search: true,
            searchSpan: 6,
            type: 'select',
            span: 24,
            value: false,
            dicData: [
              {
                label: '不启用',
                value: false
              },
              {
                label: '启用',
                value: true
              }
            ]
          },
          {
            label: '企业码',
            prop: 'enterpriseCode',
            searchSpan: 6,
            search: true
          },
          {
            label: '企业名称',
            prop: 'enterpriseName',
            searchSpan: 6,
            search: true
          },
          {
            label: '标签模板',
            prop: 'scmTemplateName'
          },
          {
            label: '序列号规则',
            prop: 'sequenceDefinitionName'
          }
        ]
      },
      data: [],
      properties: {}, //表单
      title: '',
      propertiesOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        detail: true,
        group: [
          {
            label: '基础信息',
            prop: 'equipmentInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '供应商编码',
                prop: 'code',
                rules: [
                  {
                    required: true,
                    message: '请输入供应商编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '供应商名称',
                prop: 'name',
                rules: [
                  {
                    required: true,
                    message: '请输入供应商名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '供应商缩写',
                prop: 'abbreviation',
                rules: [
                  {
                    required: true,
                    message: '请输入供应商缩写',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '联系人',
                prop: 'principal'
              },
              {
                label: '部门/职位',
                prop: 'position'
              },
              {
                label: '联系方式',
                prop: 'contacts'
              },
              {
                label: '供应商地址',
                prop: 'address',
                span: 24
              }
            ]
          },
          {
            label: 'SCM信息',
            prop: 'systemInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: 'SCM启用',
                prop: 'openScm',
                type: 'switch',
                span: 24,
                value: false,
                dicData: [
                  {
                    label: '不启用',
                    value: false
                  },
                  {
                    label: '启用',
                    value: true
                  }
                ],
                control: (val, form) => {
                  if (val) {
                    return {
                      enterpriseCode: { display: true },
                      enterpriseName: { display: true },
                      scmTemplateName: { display: true },
                      scmDefinitionName: { display: true }
                    };
                  } else {
                    return {
                      enterpriseCode: { display: false },
                      enterpriseName: { display: false },
                      scmTemplateName: { display: false },
                      scmDefinitionName: { display: false }
                    };
                  }
                }
              },
              {
                label: '企业码',
                prop: 'enterpriseCode',
                span: 12,
                rules: [
                  {
                    required: true,
                    message: '请填写唯一企业码，可向供应商或MES系统服务商咨询获取',
                    trigger: 'blur'
                  }
                ],
                enter: (value) => {
                  this.handleEnterPriseCode(value);
                }
              },
              { label: '企业名称', prop: 'enterpriseName', disabled: true, span: 12 },
              {
                label: '标签模板',
                prop: 'scmTemplateName',
                span: 12,
                type: 'search',
                disabled: true,
                rules: [
                  {
                    required: true,
                    message: '请选择标签模板',
                    trigger: 'blur'
                  }
                ],
                appendClick: () => {
                  this.openLabelTemplateModal();
                }
              },
              {
                label: '序列号规则',
                prop: 'scmDefinitionName',
                span: 12,
                type: 'search',
                disabled: true,
                rules: [
                  {
                    required: true,
                    message: '请选择序列号规则',
                    trigger: 'blur'
                  }
                ],
                appendClick: () => {
                  this.openSerialNumberModal();
                }
              }
            ]
          }
        ]
      },
      modalName: '',
      timer: new Date().getTime()
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.partner_add, false),
        viewBtn: this.vaildData(this.permission.partner_view, false),
        delBtn: this.vaildData(this.permission.partner_delete, false),
        editBtn: this.vaildData(this.permission.partner_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 新增
     */
    addBtn() {
      this.title = '新增';
      this.propertiesOption.detail = false;
      this.addDialog = true;
      this.$nextTick(() => {
        this.$refs.addProperties.allDisabled = false;
      });
      getPartnerScmDefault().then((res) => {
        let data = res.data.data;
        this.$set(this.properties, 'scmTemplateId', data.labelTemplateId);
        this.$set(this.properties, 'scmTemplateName', data.labelTemplate);
        this.$set(this.properties, 'scmDefinitionName', data.sequenceDefinition);
        this.$set(this.properties, 'scmDefinitionId', data.sequenceDefinitionId);
      });
    },
    rowView(row) {
      this.title = '详情';
      this.propertiesOption.detail = true;
      this.addDialog = true;
      getDetail(row.id).then((res) => {
        this.properties = this._get(res, 'data.data', {});
      });
      this.$nextTick(() => {
        this.$refs.addProperties.allDisabled = true;
      });
    },
    /**
     * 处理编辑
     */
    handleEdit(row) {
      this.title = '编辑';
      this.propertiesOption.detail = false;
      this.addDialog = true;
      getDetail(row.id).then((res) => {
        this.properties = this._get(res, 'data.data', {});
      });
      this.$nextTick(() => {
        this.$refs.addProperties.allDisabled = false;
      });
    },
    /**
     * 提交新增表单
     */
    submit() {
      this.$refs.addProperties.validate((valid, done) => {
        if (valid) {
          add(this.properties).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.addDialog = false;
            },
            (error) => {
              window.console.log(error);
            }
          );
          done();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    closeDialog() {
      this.properties = {};
      this.$refs.addProperties.resetFields();
    },
    handleEnterPriseCode(value) {
      checkScmTenant(value)
        .then((res) => {
          let data = res.data.data;
          if (data && data.enterpriseName) {
            this.properties.enterpriseName = data.enterpriseName;
          } else {
            this.properties.enterpriseName = '';
            this.$message.warning('未找到企业码，请与企业确认企业码无误！');
          }
        })
        .catch(() => {
          this.properties.enterpriseName = '';
        });
    },
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模板（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?type=MATERIAL&subTypeStr=RAW_MATERIAL_PACKAGING,ACCESSORIES',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=dalei',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '小类',
            prop: 'subType',
            type: 'select',
            search: true,
            dicData: [
              { label: '原材料包装', value: 'RAW_MATERIAL_PACKAGING' },
              { label: '辅料', value: 'ACCESSORIES' }
            ]
          },
          {
            label: '模板名称',
            prop: 'fileName',
            search: true,
            overHidden: true
          },
          {
            label: '模板代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'version'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    },
    openSerialNumberModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=material&subTypeStr=RAW_MATERIAL_PACKAGING,ACCESSORIES',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=serial',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '小类',
            prop: 'subType',
            dicData: [
              { label: '原材料包装', value: 'RAW_MATERIAL_PACKAGING' },
              { label: '辅料', value: 'ACCESSORIES' }
            ],
            type: 'select',
            search: true
          },
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'labelTemplateModal':
          this.properties.scmTemplateId = rowData.id;
          this.properties.scmTemplateName = rowData.fileName;
          break;
        case 'serialnoModal':
          this.properties.scmDefinitionId = rowData.id;
          this.properties.scmDefinitionName = rowData.name;
          break;
        default:
          break;
      }
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
</style>
